import request from '@/utils/request'

// 分页查询题目列表
export function getProblemList(params) {
  return request({
    url: '/api/problem/list',
    method: 'get',
    params: {
      pageNum: params.page || 1,
      pageSize: params.size || 10,
      title: params.title,
      difficulty: params.difficulty
    }
  })
}

// 导出题目Excel
export function exportProblems(params) {
  return request({
    url: '/api/problem/export',
    method: 'post',
    responseType: 'blob', // 重要：指定响应类型为二进制流
    data: params,
    headers: {
      'Authorization': `Bearer ${getToken()}`
    }
  }).then(handleExportFile)
}

// 获取题目详情
export function getProblemDetail(id) {
  return request({
    url: `/api/problem/${id}`,
    method: 'get'
  })
}

// 创建题目
export function createProblem(data) {
  return request({
    url: '/api/problem',
    method: 'post',
    data
  })
}

// 更新题目
export function updateProblem(data) {
  return request({
    url: '/api/problem',
    method: 'put',
    data
  })
}

// 批量删除题目
export function deleteProblems(ids) {
  return request({
    url: `/api/problem/${ids.join(',')}`,
    method: 'delete'
  })
}

// 处理文件导出的通用方法
function handleExportFile(response) {
  // 从响应头获取文件名
  const filename = decodeURIComponent(
    response.headers['content-disposition']
      .split('filename=')[1]
      .replace(/"/g, '')
  )

  // 创建Blob对象
  const blob = new Blob([response.data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })

  // 创建下载链接
  const downloadUrl = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = downloadUrl
  link.setAttribute('download', filename)

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理资源
  window.URL.revokeObjectURL(downloadUrl)
  document.body.removeChild(link)
}